﻿/*************************************************************************************

- CLR版本：        4.0.30319.42000
- 类 名 称：       MesHelperSharp
- 机器名称：       YTE
- 命名空间：       LD.Tool.MES.sharp
- 文 件 名：       MesHelperSharp
- 创建时间：       2022/7/31 19:45:25
- 作    者：       YTE
- 说   明：
- 修改时间：
- 修 改 人：
  *************************************************************************************/

using LD.Host;
using LD.Host.Sqlguar;
using LD.Host.项目;
using LD.PLC;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Shapes;

namespace LD.Tool
{
    [Tool(Text = "DB删除", FrmParam = "ToolDeleteDBFrm", ToolType = ToolEnum.项目)]

    public class ToolDeleteDB : BaseTool
    {
        private TB_Tool _tool;
        private DeleteDBInfo _param;
        public ToolDeleteDB()
        {
        }
        public override OpResult Execute(TB_Tool model)
        {
            _tool = model;
            try
            {
                stopwatch.Start();
                if (model.Param != null)
                {
                    _param = Newtonsoft.Json.JsonConvert.DeserializeObject<DeleteDBInfo>(model.Param);
                    if (_param != null)
                    {
                        //thread = new Thread(ToolDeleteDBFrm.ThreadDeleteDB);

                        if (DateTime.Now >= Convert.ToDateTime(_param.targetTime))
                        {
                            DeleteDBFile();
                            // 可以根据需要调整等待间隔   一天
                            //Thread.SpinWait(1 * 24 * 60 * 60);

                            //删除成功后调至下个阶段
                            DateTime targetTime = DateTime.Now.AddDays(_param.cob_datadays_out).Date.AddHours(8);
                            var param = new DeleteDBInfo()
                            {
                                txt_Val_out = _param.txt_Val_out,
                                txt_plcAddress_out = _param.txt_plcAddress_out,
                                cob_datadays_out = _param.cob_datadays_out,
                                targetTime = targetTime,
                            };
                            _tool.Param = Newtonsoft.Json.JsonConvert.SerializeObject(param);

                        }
                        if (!string.IsNullOrEmpty(_param.txt_plcAddress_out))//PLC触发删除
                        {
                            ushort val16 = 0;
                            if (ushort.TryParse(_param.txt_Val_out.ToString(), out val16))
                            {
                                var op16 = PLCFactory.Instance.ReadInt16(_param.txt_plcAddress_out);
                                if (op16.IsSuccess)
                                {
                                    if (op16.Content == val16)
                                    {
                                        var op162 = PLCFactory.Instance.Write(_param.txt_plcAddress_out, 0);
                                        //处理删除的db
                                        DeleteDBFile();

                                        isSuccess = true;
                                        Log(model, "PLC触发删除成功", LogLevel.一般);
                                    }
                                }
                            }
                            else
                                Log(model, "数据格式错误", LogLevel.警告);
                        }
                        isSuccess = true;
                    }
                }
                goto togo;

                if (!isSuccess)
                    EchoPLC(model.EchoPLC);
                togo:;
            }
            catch (Exception ex)
            {
                Log(model, ex.Message, LogLevel.严重);
            }
            finally
            {

                stopwatch.Stop();
            }
            return new OpResult() { IsSuccess = isSuccess, Message = message, ExecuteTime = stopwatch.ElapsedMilliseconds };
        }
        public void DeleteDBFile()
        {
            try
            {

                // 删除文件
                string filePath = AppDomain.CurrentDomain.BaseDirectory + "Config\\db";  // 替换成要删除的文件路径
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                    DBHelper.Instance.Sql.CodeFirst.InitTables(typeof(TB_ScrewData));//总螺丝数据
                    DBHelper.Instance.Sql.CodeFirst.InitTables(typeof(TB_ScrewDetailData));//单孔螺丝数据
                    DBHelper.Instance.Sql.CodeFirst.InitTables(typeof(TB_PressData));//螺丝查询数据（也可为压电池数据）
                                                                                     // Log(_tool, "文件删除成功！", LogLevel.一般);
                }
                //删除螺丝机的ScrewData文件
                string screwpath = "D:\\ScrewData";//设置目录
                DateTime limit = DateTime.Now.AddDays(-_param.cob_datadays_out);
                DirectoryInfo directory = new DirectoryInfo(screwpath);
                if (directory.Exists)
                {
                    var files = directory.GetFiles("*.*", SearchOption.AllDirectories);
                    foreach (FileInfo file in files)
                    {
                        if (file.LastWriteTime < limit)//删除修后后的日期  LastWriteTime  CreationTime
                        {
                            file.Delete();
                        }
                    }
                }
            }
            catch (Exception er)
            {

            }
        }


    }
    public class DeleteDBInfo
    {
        public string txt_plcAddress_out { get; set; }
        public dynamic txt_Val_out { get; set; }
        public int cob_datadays_out { get; set; }
        public DateTime targetTime { get; set; }
    }
}
